﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace desktop
{
    public partial class DragIn : DesktopForm
    {
        Point p;
        XmlDocument doc;
        private string exePath;
        private bool IsCopy = true;
        Home home = null;

        public DragIn()
        {
            InitializeComponent();
            exePath = Application.StartupPath;
            doc = Home.doc;
        }
        public DragIn(Home form)
        {
            p = form.Location;
            p.Y = p.Y - 40;
            p.X = p.X - 10;
            this.TopMost = true;

            exePath = Application.StartupPath;
            doc = Home.doc;

            XmlNode xn = doc.SelectSingleNode("Desktop");
            XmlNode xnl = xn.SelectSingleNode("Application");
            var xnl1 = (XmlElement)xnl.SelectSingleNode("DropType");
            IsCopy = bool.Parse(xnl1.GetAttribute("value"));

            home = form;
            InitializeComponent();
        }

        private void DragIn_Load(object sender, EventArgs e)
        {
            p.X += 10;
            p.Y += 40;
            this.Location = p;
            this.Size = home.Size;
        }

        private void DragIn_DragDrop(object sender, DragEventArgs e)
        {
            string src = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            AddApp(src);
            //home.AppendIcon("json");
            home.Rerun();
            this.Close();
        }

        private void DragIn_MouseLeave(object sender, EventArgs e)
        {
            home.SetDrop(true);
            this.Close();
        }
        private void DragIn_DragLeave(object sender, EventArgs e)
        {
            home.SetDrop(true);
            this.Close();
        }

        private void DragIn_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }

        /// <summary>
        /// 添加xml节点
        /// </summary>
        /// <param name="parent">父节点（对象 doc）</param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        private void AddXml(XmlNode parent, string elementName, List<Models.Key_Value> keyValue)
        {
            XmlElement xelKey = doc.CreateElement(elementName);
            foreach (var item in keyValue)
            {
                XmlAttribute xelType = doc.CreateAttribute(item.key);
                xelType.Value = item.value;
                xelKey.SetAttributeNode(xelType);
            }
            parent.AppendChild(xelKey);
            doc.Save(Home.configPath);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="src">资源地址</param>
        /// <param name="des">目标地址（将要保存的位置）</param>
        /// <param name="number">排序</param>
        /// <param name="gather">收藏夹</param>
        /// <returns></returns>
        private List<Models.Key_Value> GetXml_OuterFile(string src, string des, int number, Models.OuterFileType type)
        {
            string t = string.Empty;
            if (type == Models.OuterFileType.File)
                t = "file";
            if (type == Models.OuterFileType.Folder)
                t = "folder";
            if (type == Models.OuterFileType.Gather)
                t = "gather";
            List<Models.Key_Value> k_v = new List<Models.Key_Value>();
            k_v.Add(new Models.Key_Value()
            {
                key = "originalPath",
                value = src
            });
            k_v.Add(new Models.Key_Value()
            {
                key = "nowPath",
                value = des
            });
            k_v.Add(new Models.Key_Value()
            {
                key = "type",
                value = t
            });
            k_v.Add(new Models.Key_Value()
            {
                key = "number",
                value = number.ToString()
            });
            return k_v;
        }

        private void AddApp(string src)
        {
            if (File.Exists(src))
            {
                string RelativeSrc = Path.Combine("NewFolder\\exe\\", src.GetName());
                string FileSrc = Path.Combine(exePath, RelativeSrc);
                if (System.IO.File.Exists(FileSrc))
                {
                    MessageBox.Show("存在同名文件：" + src.GetName());
                }
                else
                {
                    if (CopyFile(src, FileSrc, IsCopy))
                    {
                        var document = doc.SelectSingleNode("Desktop").SelectSingleNode("DesktopInfo");
                        var number = document.ChildNodes.Count + 1;
                        List<Models.Key_Value> k_v = GetXml_OuterFile(src, RelativeSrc, number, Models.OuterFileType.File);
                        AddXml(document, "OuterFile", k_v);
                    }
                }
            }
            else
            {
                // 文件夹移入
                string fullFolder = exePath + "\\NewFolder\\exe\\";
                if (!Directory.Exists(fullFolder + src.GetName()))
                {
                    // 取消复制文件夹
                    //CopyDirectory(src, fullFolder);

                    var document = doc.SelectSingleNode("Desktop").SelectSingleNode("DesktopInfo");
                    var number = document.ChildNodes.Count + 1;
                    string des = fullFolder + src.GetName();
                    List<Models.Key_Value> k_v = GetXml_OuterFile(src, des, number, Models.OuterFileType.Folder);
                    AddXml(document, "OuterFile", k_v);
                }
                else
                {
                    MessageBox.Show("存在同名文件夹：" + src.GetName());
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="src"></param>
        /// <param name="des"></param>
        /// <param name="isCopy">true：复制文件、false：移动文件</param>
        private bool CopyFile(string src, string des, bool isCopy = true)
        {//src.GetExtensionName().ToLower() == "exe" || src.GetExtensionName().ToLower() == "lnk"
            try
            {
                string path;
                if (PublicWay.IconType(src) == Models.MarkType.AppName)
                {
                    path = exePath + "\\NewFolder\\icon\\" + src.GetName() + ".PNG";
                    Image img = System.Drawing.Icon.ExtractAssociatedIcon(src).ToBitmap();
                    img.Save(path);
                }
                else if (PublicWay.IconType(src) == Models.MarkType.Image)
                {
                    //File.Copy(src, des);
                }
                else
                {
                    path = exePath + "\\NewFolder\\icon\\" + src.GetExtensionName() + ".PNG";
                    if (!File.Exists(path))
                    {
                        Image img = System.Drawing.Icon.ExtractAssociatedIcon(src).ToBitmap();
                        img.Save(path);
                    }
                }
                if (isCopy)
                    File.Copy(src, des);
                else
                    File.Move(src, des);
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }

        }

        private void CopyDirectory(string srcPath, string desPath)
        {
            string folderName = srcPath.GetName();
            string desfolderdir = desPath + folderName;
            if (!Directory.Exists(desfolderdir))
            {
                Directory.CreateDirectory(desfolderdir);
            }
            string[] filenames = Directory.GetFileSystemEntries(srcPath);
            foreach (string file in filenames)
            {
                if (Directory.Exists(file))
                {
                    string currentdir = desfolderdir + "\\" + file.GetName();
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }
                    CopyDirectory(file, desfolderdir + "\\");
                }
                else
                {
                    string srcfileName = file.GetName();
                    srcfileName = desfolderdir + "\\" + srcfileName;
                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }
                    //File.Copy(file, srcfileName);
                    CopyFile(file, srcfileName, IsCopy);
                }
            }
        }



        //private void button1_Click(object sender, EventArgs e)
        //{
        //    string path = @"D:\Code\.NET Code\desktop\desktop\bin\Debug\NewFolder\exe";
        //    string path1 = @"D:\Code\.NET Code\desktop\desktop\bin\Debug\NewFolder\exe\腾讯QQ.Ink";
        //    string name = path.GetName();
        //    name = path.GetFileNameWithoutExtension();
        //    name = path1.GetName();
        //    name = path1.GetFileNameWithoutExtension();
        //}

    }
}
